<template>
  <div ref="barRef"></div>
</template>
<script setup>
import { ref, onBeforeUnmount } from 'vue'
import echarts from '@/utils/echarts'

//柱状图
const barRef = ref(null)
let barCharts = null

const initData = ({ x, y }) => {
  if (!barCharts) {
    barCharts = echarts.init(barRef.value)
  }

  let maxAmount = 0
  const yMap = {
    '接电话数量': [],
    '收回金额': [],
    '未接电话数量': [],
    '跟进数量': [],
  }
  y.forEach(item => {
    maxAmount = Math.max(maxAmount, item['收回金额'] || 0);
    yMap['收回金额'].push(item['收回金额'] || 0)
    yMap['接电话数量'].push(item['接电话数量'] || 0)
    yMap['未接电话数量'].push(item['未接电话数量'] || 0)
    yMap['跟进数量'].push(item['跟进数量'] || 0)
  })

  const option = {
    legend: {
      data: ['接电话数量', '收回金额', '未接电话数量', '跟进数量']
    },
    grid: {
      left: 32,
      right: Math.max(32, String(maxAmount).length * 10), // 根据最大金额长度动态调整右边距
      bottom: 48,
    },
    tooltip: {
      trigger: 'axis', // 触发方式为坐标轴（整块显示）
      axisPointer: {
        // 坐标轴指示器配置
        type: 'shadow', // 阴影指示器（或 'line' 直线指示器）
      },
    },
    xAxis: {
      data: x,
      type: 'category',
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left',
      },
      {
        type: 'value',
        name: '金额',
        position: 'right',
      }
    ],
    series: [
      {
        type: 'bar',
        name: '接电话数量',
        data: yMap['接电话数量'],
        yAxisIndex: 0,
        itemStyle: { color: '#5a88e7' },
        barGap: '0%',
        barCategoryGap: '40%',
      },
      {
        type: 'bar',
        name: '收回金额',
        yAxisIndex: 1,
        data: yMap['收回金额'],
        itemStyle: { color: '#78b9c3' },
        barGap: '0%',
        barCategoryGap: '40%'
      },
      {
        type: 'bar',
        name: '未接电话数量',
        yAxisIndex: 0,
        data: yMap['未接电话数量'],
        itemStyle: { color: '#68a361' },
        barGap: '0%',
        barCategoryGap: '40%'
      },
      {
        type: 'bar',
        name: '跟进数量',
        yAxisIndex: 0,
        data: yMap['跟进数量'],
        itemStyle: { color: '#ecbe55' },
        barGap: '0%',
        barCategoryGap: '40%'
      },
    ],
  }
  barCharts.setOption(option)
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  barCharts.resize()
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  barCharts.dispose()
})

defineExpose({
  initData,
})
</script>
<style lang="scss" scoped></style>
